<template>
    <div class="main_tabs">
        <div class="mhg-tabs">
            <draggable v-model="categorys" @end="handleCategoryDragEnd(e)">
                <template #item="{ element }">
                    <div :id="element">
                        <a-divider>{{ element }}</a-divider>
                        <draggable v-model="bookmarks[element]" @end="handleTabDragEnd(e, element)" class="mhg-apps">
                            <template #item="{ element }">
                                <div class="mhg-apps-item">
                                    <a-dropdown :trigger="['contextmenu']">
                                        <div class="mhg-apps-item-content" @click="openNewWindow(element.url)">
                                            <p class="mhg-apps-item-title">{{ element.title }}</p>
                                            <p class="mhg-apps-item-desc">{{ element.desc }}</p>
                                        </div>
                                        <template #overlay>
                                            <a-menu @click="onMenuClick($event, element)">
                                                <a-menu-item key="1">编辑</a-menu-item>
                                                <a-menu-item key="2">删除</a-menu-item>
                                            </a-menu>
                                        </template>
                                    </a-dropdown>
                                </div>
                            </template>
                        </draggable>
                    </div>
                </template>
            </draggable>
            <a-modal v-model:open="editModalVisible" entered @ok="updateForm">
                <a-form :model="formState" layout="vertical">
                    <a-form-item label="标题">
                        <a-input v-model:value="formState.title" />
                    </a-form-item>
                    <a-form-item label="描述">
                        <a-input v-model:value="formState.desc" />
                    </a-form-item>
                    <a-form-item label="url">
                        <a-input v-model:value="formState.url" />
                    </a-form-item>
                    <a-form-item label="分类">
                        <a-input v-model:value="formState.category" />
                    </a-form-item>
                    <a-form-item label="排序">
                        <a-input v-model:value="formState.sort" />
                    </a-form-item>
                </a-form>
            </a-modal>
            <a-modal v-model:open="deleteModalVisible" title="是否删除" @ok="deleteForm">
                <p>确认删除吗？</p>
            </a-modal>
        </div>
        <a-anchor :items="tabAnchor" class="mian-anchor" :getCurrentAnchor="getCurrentAnchor" @click="anchorClick" />
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useWindowSize } from '@vueuse/core'
import { getStorage } from '@/utils/api'
import { getAllBookmarks, deleteBookmark, updateBookmark } from '@/utils/api'
import { message } from 'ant-design-vue';
import draggable from 'vuedraggable';


message.config({
    maxCount: 1,
});


const { width } = useWindowSize()
const itemWidth = ref('33.3%')
const tabs = ref([]);

const bookmarks = ref({});

const categorys = ref([]);

const tabAnchor = ref([]);

watch(bookmarks, (value) => {
    categorys.value = Object.keys(value)
    console.log(bookmarks.value)
})

watch(categorys, (value) => {
    // 生成锚点
    tabAnchor.value = []
    for (let i = 0; i < value.length; i++) {
        tabAnchor.value.push({
            key: value[i],
            title: value[i]
        })
    }
})

const editModalVisible = ref(false);

const deleteModalVisible = ref(false);

const formState = ref({
    id: '',
    title: '',
    desc: '',
    url: '',
    category: '',
    sort: 1
})

function anchorClick(e, link) {
    document.getElementById(link.title).scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
    })
}

function getCurrentAnchor(link) {
    return document.getElementById(link.title)
}


function handleCategoryDragEnd(e) {
    let pageNum = categorys.value.length
    for (let i = 0; i < pageNum; i++) {
        let marks = bookmarks.value[categorys.value[i]]
        let markNum = marks.length
        for (let j = 0; j < markNum; j++) {
            marks[j].sort = (pageNum - i) * 100 + markNum - j
            formState.value = marks[j]
            updateForm()
        }
    }
}

function handleTabDragEnd(e, category) {
    let marks = bookmarks.value[category]
    // 获取所有的sort
    const sort = marks.map((item) => item.sort)
    sort.sort((a, b) => b - a)
    for (let i = 0; i < marks.length; i++) {
        marks[i].sort = sort[i]
        formState.value = marks[i]
        updateForm()
    }

}


function updateForm() {
    updateBookmark(JSON.parse(JSON.stringify(formState.value))).then((res) => {
        message.success('更新成功');
        getBookmarks();
        editModalVisible.value = false;
    }).catch((err) => {
        message.error('更新失败');
        editModalVisible.value = false;
    })
}

function deleteForm() {
    deleteBookmark(formState.value.id).then((res) => {
        message.success('删除成功');
        getBookmarks();
        deleteModalVisible.value = false;
    }).catch((err) => {
        message.error('删除失败');
        deleteModalVisible.value = false;
    })
}

// 获取所有书签 并根据 category 分类

function getBookmarks() {

    getAllBookmarks().then((res) => {
        res.sort((a, b) => b.sort - a.sort);
        bookmarks.value = res.reduce((acc, bookmark) => {
            const { category } = bookmark;
            acc[category] = acc[category] || []; // 如果类别不存在，则创建一个空数组
            acc[category].push(bookmark);
            return acc;
        }, {});
    }).catch((err) => {
        console.log(err)
    })
}

getBookmarks();

watch(width, (value) => {
    if (value < 768) {
        itemWidth.value = '100%'
    } else if (value < 1280) {
        itemWidth.value = '50%'
    } else {
        itemWidth.value = '33.3%'
    }
})

function openNewWindow(url) {
    window.open(url, '_target')
}

function getTabs() {
    getStorage('tabs').then((res) => {
        tabs.value = res
    })
}

function onMenuClick(e, app) {
    if (e.key === '1') {
        formState.value = app
        editModalVisible.value = true
    } else if (e.key === '2') {
        formState.value = app
        deleteModalVisible.value = true
    }
}

getTabs()



</script>

<style>
.main_tabs {
    width: 100%;
    zoom: 1;
    display: flex;
    overflow: auto;
    height: calc(100vh - 152px);
}

.mian-anchor {
    position: fixed;
    right: 0;
    width: 80px;
}

.mhg-tabs {
    padding: 10px;
    width: calc(100% - 80px);
}

.mhg-apps {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
}

.mhg-apps-item {
    width: v-bind(itemWidth);
    min-width: 200px;
    padding: 10px;
    min-height: 80px;
}

.mhg-apps-item-content {
    background-color: white;
    border-radius: 10px;
    padding: 20px 10px 10px 30px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.mhg-apps-item-content:hover {
    transform: translateY(-5px);
    cursor: pointer;
}

.mhg-apps-item-title {
    font-size: 1.3em;
    font-weight: bold;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 200px;
}

.mhg-apps-item-desc {
    font-size: 1.1em;
    color: #999;
}
</style>